package com.hejjon.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hejjon.bean.LibrarySettingParam;
import com.hejjon.core.constant.SettingConstants;
import com.hejjon.core.domain.entity.LibrarySetting;
import com.hejjon.core.enumer.DeleteFlagEnum;
import com.hejjon.core.exception.BusinessException;
import com.hejjon.core.utils.StrUtil;
import com.hejjon.domain.vo.LibrarySettingItemVO;
import com.hejjon.domain.vo.LibrarySettingVO;
import com.hejjon.mapper.LibrarySettingMapper;
import com.hejjon.service.ILibrarySettingService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 知识对象节点配置
 */
@Service
public class LibrarySettingServiceImpl extends ServiceImpl<LibrarySettingMapper, LibrarySetting>
        implements ILibrarySettingService {


    @Override
    public LibrarySettingItemVO getLibrarySettingItem(String settingName) {
        SettingConstants.SettingsEnum settingsEnum = SettingConstants.SettingsEnum.getInstance(settingName);
        if (settingsEnum == null) {
            throw new BusinessException("设置项未知！");
        }
        LibrarySettingItemVO vo = new LibrarySettingItemVO();
        vo.setName(settingsEnum.getName());
        vo.setDesc(settingsEnum.getDesc());
        vo.setSettingNodeList(settingsEnum.getSettingNodeList());
        return vo;
    }

    @Override
    public Map<String, LibrarySettingItemVO> getLibraryInitSettingsMap() {
        return Arrays.stream(SettingConstants.SettingsEnum.values()).collect(Collectors.toMap(SettingConstants.SettingsEnum::getName,
                item -> new LibrarySettingItemVO(item.getName(), item.getDesc(), item.getUiType(),
                        item.getDefaultValue(), item.getSettingNodeList())));
    }

    @Override
    public boolean saveSetting(LibrarySettingParam param) {
        String id = param.getId();
        if (StringUtils.isBlank(id)) {
            LibrarySetting entity = new LibrarySetting();
            entity.setId(StrUtil.getUUID());
            entity.setKnoNodeId(param.getNodeId());
            entity.setContent(param.getContent());
            entity.setCreateBy("admin");
            entity.setCreateTime(new Date());
            entity.setDeleteFlag(DeleteFlagEnum.NO.getCode());
            int insert = baseMapper.insert(entity);
            return insert > 0;
        } else {
            LibrarySetting updEntity = baseMapper.selectById(param.getId());
            if (updEntity == null) {
                throw new BusinessException("节点配置不存在, 请检查!");
            }
            // 更新 content 中的指定字段
            JSONObject contJson = JSON.parseObject(updEntity.getContent());
            JSONObject paramContent = JSON.parseObject(param.getContent());
            Set<String> keySet = paramContent.keySet();
            for (String key : keySet) {
                contJson.put(key, paramContent.getString(key));
            }
            updEntity.setContent(JSON.toJSONString(contJson));
            updEntity.setUpdateBy("admin");
            updEntity.setUpdateTime(new Date());
            return baseMapper.updateById(updEntity) > 0;
        }
    }


    @Override
    public LibrarySettingVO getByNodeId(String nodeId) {
        LibrarySetting librarySetting = baseMapper.selectByKnoNodeId(nodeId);
        LibrarySettingVO vo = new LibrarySettingVO();
        vo.setNodeId(nodeId);
        if (librarySetting == null) {
            vo.setSettingsMap(getLibraryInitSettingsMap());
            return vo;
        }
        vo.setSettingId(librarySetting.getId());
        String content = librarySetting.getContent();
        try {
            JSONObject contentObj = JSON.parseObject(content);
            Map<String, LibrarySettingItemVO> map = new HashMap<>();
            Map<String, LibrarySettingItemVO> libraryInitSettingsMap = getLibraryInitSettingsMap();
            Set<String> keys = libraryInitSettingsMap.keySet();
            for (String key : keys) {
                // 当前节点设置过该配置项,则取设置的值
                if (contentObj.containsKey(key)) {
                    JSONObject obj = contentObj.getJSONObject(key);
                    LibrarySettingItemVO itemVO = JSON.parseObject(obj.toJSONString(), LibrarySettingItemVO.class);
                    map.put(key, itemVO);
                } else {
                    // 未配置过就取默认初始化的
                    LibrarySettingItemVO initVO = libraryInitSettingsMap.get(key);
                    map.put(key, initVO);
                }
            }
            vo.setSettingsMap(map);
        } catch (Exception e) {
            throw new BusinessException("配置内容解析异常: " + e.getMessage());
        }
        return vo;
    }

}
